<template>
	<view class="blindbox-container">
		<view v-if="loading" class="loading-mask">
			<!-- <w-image :src="info.main_image" mode="WidthFix" :width="193" :height="193"></w-image> -->
		</view>
		<view :id="containerId" class="lottie-box flex flex-ai-center flex-js-center"></view>
	</view>
</template>


<script>
	import lottie from "lottie-web";
	import { replaceLottieImages } from "@/utils/lottieReplace.js";


	export default {
		name: "BlindBoxs",
		props: {
			prizeImg: {
				type: String,
				required: true
			},
			jsonPath: {
				type: String,
				default: "/static/allBlindBox.json"
			},
			autoPlay: {
				type: Boolean,
				default: false
			},
			replaceMap: {
				type: Object,
				default: () => ({})
			},
			info:{
				type: Object,
				default: () => ({})
			}
		},
		data() {
			return {
				animation: null,
				loading: true,
				containerId: "lottie-" + Math.random().toString(36).substr(2, 9)
			};
		},
		mounted() {
			this.initLottie();
		},
		beforeUnmount() {
			this.animation && this.animation.destroy();
		},
		methods: {
			emitOpened() {
				this.$emit('opened');
			},
			replay() {
				if (this.animation) this.animation.goToAndPlay(0, true);
			},
			async initLottie() {
				const res = await fetch(this.jsonPath);
				let data = await res.json();
				const map = {
					...this.replaceMap
				};
				if (this.prizeImg) {
					map["开盲盒_[00000-00074].png_0"] = this.prizeImg;
				}
				data = await replaceLottieImages(data, map, true);
				this.animation = lottie.loadAnimation({
					container: document.getElementById(this.containerId),
					renderer: "svg",
					loop: false,
					autoplay: this.autoPlay,
					animationData: data,
					rendererSettings: {
						preserveAspectRatio: "xMidYMid slice"
					}
				});


				this.animation.addEventListener('complete', () => {
					this.emitOpened();
				});


				this.loading = false;
			}
		}
	};
</script>


<style scoped>
	.blindbox-container {
		position: relative;
		width: 100%;
		height: 60vh;
	}

	.loading-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		/* background: #ffffffaa; */
		z-index: 10;
	}

	.lottie-box {
		width: 100%;
		height: 100%;
	}
</style>